package kiwi.assist.dev.guieditor.command {
	import kiwi.assist.dev.guieditor.event.GUIOperateEvent;
	import kiwi.assist.dev.guieditor.model.UiDetailVO;

	import org.robotlegs.mvcs.Command;

	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.geom.Rectangle;

	/**
	 * 移动ui的图层
	 * @author zhangming.luo
	 */
	public class MoveUiLayerCommand extends Command {
		[Inject]
		public var event : GUIOperateEvent;
		[Inject]
		public var detail : UiDetailVO;
		private var ui : DisplayObject;

		override public function execute() : void {
			super.execute();
			ui = event.targetUi;
			var step : int = event.param;
			var canvas : DisplayObjectContainer = ui.parent.parent;
			var bounds : Rectangle = ui.parent.getBounds(canvas);
			var uiList : Array = [];
			if (step == int.MAX_VALUE) {
				canvas.addChild(ui.parent);
			} else if (step == int.MIN_VALUE) {
				canvas.addChildAt(ui.parent, 0);
			} else {
				// 获得所有的上下层ui(有重叠的)
				for (var i : int = 0;i < canvas.numChildren;i++) {
					var child : DisplayObject = canvas.getChildAt(i);
					if (child.getBounds(canvas).intersects(bounds)) {
						uiList.push(child);
					}
				}
				var index : int = Math.max(Math.min(uiList.indexOf(ui.parent) + step, uiList.length - 1), 0);
				canvas.addChildAt(ui.parent, canvas.getChildIndex(uiList[index]));
			}
			detail.backgroundSkinList = detail.backgroundSkinList.sort(sortFunc);
			detail.uiList = detail.uiList.sort(sortFunc);
		}

		private function sortFunc(lh : DisplayObject, rh : DisplayObject) : int {
			return lh.parent.parent.getChildIndex(lh.parent) - rh.parent.parent.getChildIndex(rh.parent);
		}
	}
}
